package handler

import (
	"developer-branch/api/request"
	"developer-branch/glodal"
	"developer-branch/internal/model"
	jwt "developer-branch/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
)

func UserUp(c *gin.Context) {
	var req request.UserUp
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	glodal.DB.Where("name = ?", req.Name).Find(&user)
	if user.ID == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "该用户不存在，无法登陆",
			"data": err.Error(),
		})
		return
	}
	if req.Password != user.Password {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "密码有误",
			"data": err.Error(),
		})
		return
	}
	token, _ := jwt.NewJWT("2210y").CreateToken(jwt.CustomClaims{
		ID: user.ID,
	})
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登陆成功",
		"data": token,
	})
}

func UserList(c *gin.Context) {
	var user []model.User
	err := glodal.DB.Find(&user).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "展示失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": user,
	})
}
